import color from "@/maps/color";
import colorFn from "css-color-function";
//v-color={
//   p:'',// p代表位置 text , border , all ,为空则是背景
//   v:'#ccc',//v代表颜色,直接输入颜色或者使用maps/colorjs里的颜色key
//   t:100,//对应滤镜的key，值（%）的数字，可以有多个滤镜
// }
function setColor(el, { value }) {
  let { p: arg } = value;
  let modifiers = { ...value, p: null, v: null };
  value = value.v; //v代表颜色
  let nameMap = {
    t: "tint",
    s: "shade",
    a: "alpha", //透明度
    h: "hue", //色调
    r: "red",
    g: "green",
    b: "blue",
    u: "saturation", //饱和度
    m: "blend", //合并颜色
  };
  let val = color[value] || value;
  let keys = Object.keys(modifiers).filter((v) => modifiers[v] !== null);
  if (keys.length > 0) {
    keys.forEach((v) => {
      if (v.match(/\w*\(?.\)/)) {
        let names = nameMap[v.match(/(.+)\(/)?.[1]];
        let vals = v.match(/\((.+)\)/)?.[1];
        if (names && vals && val) {
          let unit = "%";
          if (names === "hue" || names === "blend") {
            unit = "";
          }
          if (names === "blend") {
            let arg = vals.split(",");
            if (arg[0] && arg[1]) {
              val = colorFn.convert(
                `color(${val} ${names}(${arg[0]} ${arg[1]}))`
              );
            }
          } else {
            val = colorFn.convert(`color(${val} ${names}(${vals}${unit}))`);
          }
        }
      }
    });
  }
  if (arg === "text") {
    el.style.color = val;
  } else if (arg === "border") {
    el.style.borderColor = val;
  } else {
    if (arg === "all") {
      el.style.borderColor = val;
      el.style.color = val;
    }
    el.style.backgroundColor = val;
  }
}
// console.log(colorFn.convert('color(#f00 shade(10%))'))
// console.log(colorFn.convert('color(#f00 tint(10%))'))
// console.log(colorFn.convert('color(#f00 alpha(10%))'))
const vColor = {
  inserted() {
    setColor(...arguments);
  },
  updated() {
    setColor(...arguments);
  },
};
export default vColor;
